package com.figure.web.controller.security;

import com.figure.common.utils.StringUtil;
import com.figure.service.dto.PageDto;
import com.figure.service.dto.security.AccountDto;
import com.figure.service.dto.security.ResourcesDto;
import com.figure.service.dto.security.RoleDto;
import com.figure.service.provide.security.ISecurityService;
import com.figure.web.controller.BaseController;
import com.figure.web.util.APIResult;
import com.figure.web.util.TreeUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Weber on 3/22/2016.
 */
@RequestMapping(value = "/admin/security")
@Controller
public class SecurityController extends BaseController {
    static Logger logger = LoggerFactory.getLogger(SecurityController.class);

    @Autowired
    private ISecurityService securityService;

//    @RequestMapping(value = "login", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
//    public String login(HttpServletRequest request) {
//        request.removeAttribute("error");
//        return "/login";
//    }

//    @RequestMapping(value = "login", method = RequestMethod.POST)
//    public Object login(String username, String password, HttpServletRequest request) {
//        try {
//            if (!request.getMethod().equals("POST")) {
//                request.setAttribute("error", "支持POST方法提交！");
//            }
//            if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
//                request.setAttribute("error", "用户名或密码不能为空！");
//                return "/login";
//            }
//            // 想要得到 SecurityUtils.getSubject()　的对象．．访问地址必须跟ｓｈｉｒｏ的拦截地址内．不然后会报空指针
//            Subject user = SecurityUtils.getSubject();
//            // 用户输入的账号和密码,,存到UsernamePasswordToken对象中..然后由shiro内部认证对比,
//            // 认证执行者交由ShiroDbRealm中doGetAuthenticationInfo处理
//            // 当以上认证成功后会向下执行,认证失败会抛出异常
//            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
//            try {
//                user.login(token);
//            } catch (LockedAccountException lae) {
//                token.clear();
//                request.setAttribute("error", "用户已经被锁定不能登录，请与管理员联系！");
//                return "/login";
//            } catch (ExcessiveAttemptsException e) {
//                token.clear();
//                request.setAttribute("error", "账号：" + username + " 登录失败次数过多,锁定10分钟!");
//                return "/login";
//            } catch (AuthenticationException e) {
//                token.clear();
//                request.setAttribute("error", "用户或密码不正确！");
//                return "/login";
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            request.setAttribute("error", "登录异常，请联系管理员！");
//            return "/login";
//        }
//        return "/wel";
//    }

    @RequestMapping(value = "login")
    public APIResult login(Model model, String username, String password, HttpServletRequest request) {
        String errorMessage = ""; //登陆提示信息
        boolean isAuth = false; //登陆提示信息
        try {
            if (!request.getMethod().equals("POST")) {
                return APIResult.failResult(100, "支持POST方法提交！");
//                request.setAttribute("error", "支持POST方法提交！");
//                errorMessage = "支持POST方法提交！";
            }
            if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
                return APIResult.failResult(101, "用户名或密码不能为空！");
//                errorMessage = "用户名或密码不能为空！";
//                request.setAttribute("error", "用户名或密码不能为空！");
//                return "/login";
            }
            // 想要得到 SecurityUtils.getSubject()　的对象．．访问地址必须跟ｓｈｉｒｏ的拦截地址内．不然后会报空指针
            Subject user = SecurityUtils.getSubject();
            // 用户输入的账号和密码,,存到UsernamePasswordToken对象中..然后由shiro内部认证对比,
            // 认证执行者交由ShiroDbRealm中doGetAuthenticationInfo处理
            // 当以上认证成功后会向下执行,认证失败会抛出异常
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            try {
                user.login(token);
                isAuth = user.isAuthenticated();
            } catch (LockedAccountException lae) {
                token.clear();
                return APIResult.failResult(102, "用户已经被锁定不能登录，请与管理员联系！");
//                errorMessage = "用户已经被锁定不能登录，请与管理员联系！";
//                request.setAttribute("error", "用户已经被锁定不能登录，请与管理员联系！");
//                return "/login";
            } catch (ExcessiveAttemptsException e) {
                token.clear();
//                request.setAttribute("error", "账号：" + username + " 登录失败次数过多,锁定10分钟!");
//                return "/login";
                return APIResult.failResult(103, "账号：" + username + " 登录失败次数过多,锁定10分钟!");
//                errorMessage = "账号：\" + username + \" 登录失败次数过多,锁定10分钟!";
            } catch (AuthenticationException e) {
                token.clear();
//                request.setAttribute("error", "用户或密码不正确！");
//                return "/login";
                return APIResult.failResult(103, "用户或密码不正确！");
//                errorMessage = "用户或密码不正确！";
            }
//            UserLoginFormMap userLogin = new UserLoginFormMap();
//            Session session = SecurityUtils.getSubject().getSession();
//            userLogin.put("userId", session.getAttribute("userSessionId"));
//            userLogin.put("accountName", username);
//            userLogin.put("loginIP", session.getHost());
//            userLoginMapper.addEntity(userLogin);
//            request.removeAttribute("error");
        } catch (Exception e) {
            e.printStackTrace();
//            request.setAttribute("error", "登录异常，请联系管理员！");
//            return "/login";
            return APIResult.failResult(104, "登录异常，请联系管理员！");
//            errorMessage = "登录异常，请联系管理员！";
        }
//        model.addAttribute("errorMessage", errorMessage);
//        model.addAttribute("isAuth", isAuth);
//        if(isAuth){
//            model.addAttribute("userName", username);
//            return "index";
//        }
        return APIResult.okResult(null);
    }

    /**
     * @mod Ekko 2015-09-07
     * @throws Exception
     */
    @RequestMapping("index")
    public String index(ModelMap modelMap,HttpServletRequest reqeuest) throws Exception {
        // 获取登录的bean
        AccountDto accountDto = (AccountDto)findUserSession(reqeuest);
        if(null==accountDto){
            modelMap.put(SUCCESS, false);
            modelMap.put(MSG, "请登录系统！");
//            reqeuest.setAttribute("error", "请登录系统！");
            return "/login";
        }
        List<ResourcesDto> mps = securityService.findUserResourcess(accountDto.getId()+"");
//        List<ResFormMap> mps = resourcesMapper.findByWhere(new ResFormMap());
//        List<TreeObject> list = new ArrayList<TreeObject>();
//        for (ResFormMap map : mps) {
//            TreeObject ts = new TreeObject();
//            Common.flushObject(ts, map);
//            list.add(ts);
//        }
        TreeUtil treeUtil = new TreeUtil();
        List<ResourcesDto> ns = treeUtil.getChildTreeObjects(mps, 0);
        modelMap.put("dirList", ns);
        // 登陆的信息回传页面
        modelMap.put("userFormMap", accountDto);
        modelMap.put(SUCCESS, true);
        return "/index";
    }

    @RequestMapping("menu")
    public String menu(Model model) {
        return JSPDIR + "/index";
    }

    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public String logout() {
        // 使用权限管理工具进行用户的退出，注销登录
        SecurityUtils.getSubject().logout(); // session
        // 会销毁，在SessionListener监听session销毁，清理权限缓存
        return "/login";//"redirect:login.html.bak";
    }

    /**
     * @author Quinn He
     * @dateTime 2012-6-4 下午8:35:41
     * @param mav
     * @return org.springframework.web.servlet.ModelAndView
     */
    @RequestMapping(value = "/reg", method = RequestMethod.GET)
    protected ModelAndView regGet(final ModelAndView mav) {
        mav.setViewName("/registrate");
        return mav;
    }

    @RequestMapping(value = "roleList")
    public String roleList(String name, String status, HttpServletRequest request,ModelMap modelMap,
                           @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                           @RequestParam(value = "pageSize", defaultValue = "20") int pageSize) {
        if (pageNo < 1) {
            pageNo = 1;
        }
        if (pageSize < 1 && pageSize > 20) {
            pageSize = 20;
        }
        Integer statusv = null;
        try {
            if(StringUtil.isNotEmpty(status)){
                statusv = new Integer(status);
            }
            PageDto<RoleDto> page = securityService.queryRole(name, statusv, pageNo, pageSize);
            modelMap.put("data", page);
        } catch (Exception e) {
            e.printStackTrace();
            modelMap.put(SUCCESS, false);
            modelMap.put(MSG, "查询异常！");
        }
        modelMap.put(SUCCESS, true);
        return JSPDIR + "security/roleList";
    }
}
